import Vue from 'vue'
import Vuex from 'vuex'
import influxdb from '@/utils/influxdb'
import storage from '@/utils/storage'
import logger from '@/utils/logger'
import { LRUCache } from '@/utils/performance'

Vue.use(Vuex)

// 配置常量
const MAX_QUERY_RESULTS_SIZE = 10000 // 最大查询结果行数
const MAX_QUERY_HISTORY = 100 // 最大查询历史记录数
const RESULT_CACHE_SIZE = 20 // 结果缓存大小

export default new Vuex.Store({
  state: {
    connections: [],
    currentConnection: null,
    queryHistory: [],
    queryResults: [],
    measurements: [],
    settings: {
      theme: 'light',
      editorTheme: 'material',
      fontSize: 14,
      autoComplete: true,
      maxResultRows: MAX_QUERY_RESULTS_SIZE,
      enableCache: true
    },
    // 性能监控
    performanceMetrics: {
      lastQueryDuration: 0,
      totalQueries: 0,
      cacheHitRate: 0
    }
  },

  // 私有状态（不被序列化）
  _resultCache: new LRUCache(RESULT_CACHE_SIZE),
  
  mutations: {
    SET_CONNECTIONS(state, connections) {
      state.connections = connections
    },
    
    ADD_CONNECTION(state, connection) {
      state.connections.push(connection)
    },
    
    UPDATE_CONNECTION(state, connection) {
      const index = state.connections.findIndex(c => c.id === connection.id)
      if (index !== -1) {
        state.connections.splice(index, 1, connection)
      }
    },
    
    REMOVE_CONNECTION(state, id) {
      state.connections = state.connections.filter(c => c.id !== id)
    },
    
    SET_CURRENT_CONNECTION(state, connection) {
      state.currentConnection = connection
    },
    
    SET_QUERY_HISTORY(state, history) {
      state.queryHistory = history
    },
    
    ADD_QUERY_TO_HISTORY(state, query) {
      state.queryHistory.push(query)

      // 限制历史记录大小
      if (state.queryHistory.length > MAX_QUERY_HISTORY) {
        state.queryHistory = state.queryHistory.slice(-MAX_QUERY_HISTORY)
        logger.debug('STORE', `Query history trimmed to ${MAX_QUERY_HISTORY} entries`)
      }
    },

    SET_QUERY_RESULTS(state, results) {
      // 限制结果集大小
      if (results && results.length > state.settings.maxResultRows) {
        logger.warn('STORE', `Query results truncated from ${results.length} to ${state.settings.maxResultRows} rows`)
        state.queryResults = results.slice(0, state.settings.maxResultRows)
      } else {
        state.queryResults = results
      }
    },
    
    SET_MEASUREMENTS(state, measurements) {
      state.measurements = measurements
    },
    
    SET_SETTINGS(state, settings) {
      state.settings = { ...state.settings, ...settings }
    },

    UPDATE_PERFORMANCE_METRICS(state, metrics) {
      state.performanceMetrics = { ...state.performanceMetrics, ...metrics }
    },

    CLEAR_QUERY_RESULTS(state) {
      state.queryResults = []
      logger.debug('STORE', 'Query results cleared')
    }
  },

  actions: {
    async loadConnections({ commit }) {
      const connections = storage.loadConnections()
      commit('SET_CONNECTIONS', connections)
      
      connections.forEach(conn => {
        influxdb.createConnection(conn)
      })
      
      return connections
    },
    
    async saveConnection({ commit, state }, connection) {
      const isUpdate = !!connection.id
      const connectionData = {
        ...connection,
        id: connection.id || Date.now().toString()
      }
      
      influxdb.createConnection(connectionData)
      
      if (isUpdate) {
        // Update existing connection
        commit('UPDATE_CONNECTION', connectionData)
      } else {
        // Add new connection
        commit('ADD_CONNECTION', connectionData)
      }
      
      storage.saveConnections(state.connections)
      return connectionData
    },
    
    async removeConnection({ commit, state }, id) {
      influxdb.removeConnection(id)
      commit('REMOVE_CONNECTION', id)
      
      if (state.currentConnection && state.currentConnection.id === id) {
        commit('SET_CURRENT_CONNECTION', null)
      }
      
      storage.saveConnections(state.connections)
    },
    
    async setCurrentConnection({ commit }, connection) {
      const success = influxdb.setCurrentConnection(connection.id)
      if (success) {
        commit('SET_CURRENT_CONNECTION', connection)
      }
      return success
    },
    
    async testConnection(_, config) {
      return await influxdb.testConnection(config)
    },
    
    async executeQuery({ commit, state }, query) {
      const perfId = `store_query_${Date.now()}`
      logger.startPerformance(perfId)

      try {
        const startTime = performance.now()
        const results = await influxdb.query(query)
        const duration = performance.now() - startTime

        commit('SET_QUERY_RESULTS', results)

        const historyEntry = storage.addQueryToHistory(query)
        commit('ADD_QUERY_TO_HISTORY', historyEntry)

        // 更新性能指标
        const totalQueries = state.performanceMetrics.totalQueries + 1
        commit('UPDATE_PERFORMANCE_METRICS', {
          lastQueryDuration: duration,
          totalQueries
        })

        logger.endPerformance(perfId, { rowCount: results.length })
        logger.info('STORE', `Query executed successfully`, {
          duration: `${duration.toFixed(2)}ms`,
          rowCount: results.length
        })

        return { success: true, data: results }
      } catch (error) {
        logger.endPerformance(perfId, { error: true })
        logger.error('STORE', 'Query execution failed', error)
        return { success: false, error: error.message }
      }
    },
    
    async loadQueryHistory({ commit }) {
      const history = storage.loadQueryHistory()
      commit('SET_QUERY_HISTORY', history)
      return history
    },
    
    async loadMeasurements({ commit }) {
      logger.debug('STORE', 'Loading measurements')

      try {
        const measurements = await influxdb.getMeasurements()
        commit('SET_MEASUREMENTS', measurements)
        logger.info('STORE', `Loaded ${measurements.length} measurements`)
        return measurements
      } catch (error) {
        logger.error('STORE', 'Failed to load measurements', error)
        return []
      }
    },

    async loadSettings({ commit }) {
      logger.debug('STORE', 'Loading settings')
      const settings = storage.loadSettings()
      commit('SET_SETTINGS', settings)
      return settings
    },

    async saveSettings({ commit, state }, settings) {
      logger.info('STORE', 'Saving settings', settings)
      commit('SET_SETTINGS', settings)
      storage.saveSettings(state.settings)
      return state.settings
    },

    async getDatabases() {
      logger.debug('STORE', 'Getting databases')

      try {
        const databases = await influxdb.getDatabases()
        logger.info('STORE', `Retrieved ${databases.length} databases`)
        return databases
      } catch (error) {
        logger.error('STORE', 'Failed to get databases', error)
        return []
      }
    },

    async getServerInfo() {
      logger.debug('STORE', 'Getting server info')

      try {
        const serverInfo = await influxdb.getServerInfo()
        logger.info('STORE', 'Server info retrieved', serverInfo)
        return serverInfo
      } catch (error) {
        logger.error('STORE', 'Failed to get server info', error)
        return null
      }
    },

    // 清除查询结果（内存管理）
    clearQueryResults({ commit }) {
      commit('CLEAR_QUERY_RESULTS')
    }
  },
  
  getters: {
    hasConnections: state => state.connections.length > 0,
    isConnected: state => state.currentConnection !== null,
    recentQueries: state => state.queryHistory.slice(-10).reverse(),
    resultCount: state => state.queryResults.length,
    performanceStats: state => state.performanceMetrics
  }
})